import { Injectable } from '@angular/core';
import {Http,Response,Headers,RequestOptions,Jsonp,URLSearchParams} from "@angular/http";
import {Observable} from "rxjs/Rx";


@Injectable()
export class DataService {
  private url='/api/data.json';
  private jsonpurl="/api/jsonp";
  private posturl='/api/post';
  private postfile='/api/upload';
  constructor(private _http:Http,private _jsonp:Jsonp) { 
    
  }
  getdata():Observable<any> {
  	return this._http.get(this.url).map(this.extractdata).catch(this.catch);
  }
  extractdata(res:Response){
    console.log(res);
  	var body=res.json();
  	return body.data || '';
  }
  catch(err){
    return Observable.throw(err.statusText+err.status);
  }
  post(data):Observable<any>{
    let headers=new Headers({'Content-Type':'application/json'});
    let options=new RequestOptions({headers:headers});
    return this._http.post(this.posturl,data,options).map(this.extractdata).catch(this.catch);
  }
  jsonp(data):Observable<any>{
    let params=new URLSearchParams();
    params.set('data',JSON.stringify(data));
    params.set('callback','JSONP_CALLBACK');

    return this._jsonp.get(this.jsonpurl,{search:params}).
    map(this.extractdata).catch(this.catch);
  }
  upload(fd):Observable<any>{
      return this._http.post(this.postfile,fd).map(this.extractdata).catch(this.catch);
  }

}
